import * as auth from '@/utils/auth'
let pending = false //是否正在请求token

function getPendingStatus(resolve) {
  setTimeout(() => {
    if (!pending) {
      resolve()
    } else {
      getPendingStatus(resolve)
    }
  }, 200)
}

function awaitToken() {
  return new Promise((resolve, reject) => {
    if (pending) {
      getPendingStatus(resolve)
      return
    }
    pending = true
    uni.$api.public
      .getToken()
      .then((res) => {
        const tokenId = res.tokenId || ''
        auth.saveToken(tokenId)
        resolve(res)
        pending = false
      })
      .catch((err) => {
        reject(err)
      })
  })
}

export default awaitToken
